package com.itguigu.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itguigu.auth.service.SysMenuService;
import com.itguigu.auth.service.SysUserService;
import com.itguigu.common.exception.GuiguException;
import com.itguigu.common.jwt.JwtUtils;
import com.itguigu.common.result.Result;
import com.itguigu.common.utils.MD5;
import com.itguigu.model.system.SysUser;
import com.itguigu.vo.system.LoginVo;
import com.itguigu.vo.system.RouterVo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Slf4j
@Api(tags = "后台登录功能")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo){
        log.info("登录信息 loginvo : {}" , loginVo);
        // 根据用户名 查询数据
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, loginVo.getUsername()));

        // 判空
        if (sysUser == null) {
            // 空的直接
            throw new GuiguException(201, "用户不存在");
        }

        // 判断密码 , MD5密码比较
        // 将输入得密码 进行MD5加密 , 然后加密比较
        String inputPasswordMD5 = MD5.encrypt(loginVo.getPassword());
        if (!sysUser.getPassword().equals(inputPasswordMD5)){
            // 不相等
            throw new GuiguException(201, "密码不正确");
        }

        // 判断状态 是否被禁用
        if (sysUser.getStatus() == 0){
            // 被禁用
            throw new GuiguException(201, "用户已经被禁用 , 请联系管理员");
        }
        // 使用jwt根据用户id 和 用户名称 生成token字符串
        Map<String , Object> map = new HashMap<>();
        map.put("userId", sysUser.getId());
        map.put("username", sysUser.getUsername());
        String jwt = JwtUtils.generateJwt(map);
        log.info("jwt : {}" , jwt);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", jwt);
        return Result.success(hashMap);
    }


    @GetMapping("info")
    public Result info(HttpServletRequest request){
        // 从请求头中获取token字符串信息 => jwt
        String tokenJwt = request.getHeader("token");
        // jwt解析
        // 得到用户id  , 和 用户名称
        Claims claims = JwtUtils.ParserJwt(tokenJwt);
        Object id = claims.get("userId");
        Integer integer = (Integer) id;
        log.info(String.valueOf(integer));
//        Long userId = new Long(integer.intValue());
        Long userId = (long) integer;
//        Long userId = (long) claims.get("userId");
//        Long userId = Long.valueOf((String) idObj);
//        Long userId = (Long) claims.get("userId");
//        Long userId = 2L;
        log.info("解析得到的用户userId : {}" , userId);
        // 根据用户id 查询数据库 , 得到用户信息
        SysUser sysUser = sysUserService.getById(userId);
        // 根据用户id获取用户可以操作得菜单列表
        // 动态菜单路由构建
        List<RouterVo> routerVoList = sysMenuService.findUserMenuListByUserId(userId);
        // 根据用户id 获取用户 的 操作权限 -> 即菜单表中的权限标识字段
        List<String> permsList = sysMenuService.findUserPermsByUserId(userId);
        // 数据返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("roles", "[admin]");
        map.put("name", sysUser.getName());
        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        // 返回用户可以操作得菜单
        map.put("routers", routerVoList);
        // 返回用户可以操作得按钮
        map.put("buttons", permsList);
        return Result.success(map);
    }

    @PostMapping("logout")
    public Result logout(){
        return Result.success();
    }
}
